package cn.mumzone.pos.presenter;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.mumzone.basic.mvp.AbsPresenter;
import cn.mumzone.basic.net.http.callback.ApiCallBack;
import cn.mumzone.basic.net.response.BaseResponse;
import cn.mumzone.basic.net.response.PageListResponse;
import cn.mumzone.basic.util.ListUtil;
import cn.mumzone.basic.util.PatternUtils;
import cn.mumzone.basic.util.RxBus;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.pos.AppConstants;
import cn.mumzone.pos.event.AddGoodsEvent;
import cn.mumzone.pos.event.AddServiceEvent;
import cn.mumzone.pos.event.MemberBindEvent;
import cn.mumzone.pos.event.MemberChangeEvent;
import cn.mumzone.pos.event.RemotePriceChangeEvent;
import cn.mumzone.pos.event.SettleSuccessEvent;
import cn.mumzone.pos.event.UpdateReserveTimeEvent;
import cn.mumzone.pos.model.GoodsEntity;
import cn.mumzone.pos.model.MemberEntity;
import cn.mumzone.pos.model.ReserveOrderEntity;
import cn.mumzone.pos.model.ServerEntity;
import cn.mumzone.pos.model.ServerResultEntity;
import cn.mumzone.pos.model.ServiceEntity;
import cn.mumzone.pos.model.source.GoodsRepository;
import cn.mumzone.pos.model.source.MemberRepository;
import cn.mumzone.pos.model.source.ReserveRepository;
import cn.mumzone.pos.model.source.StockRepository;
import cn.mumzone.pos.presenter.contract.OpenOrderContract;
import cn.mumzone.pos.util.AppUtil;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Subscription;
import rx.functions.Action1;

/**
 * Created by qiuzhenhuan on 2019/6/13.
 */

public class OpenOrderPresenter extends AbsPresenter<OpenOrderContract.View, ReserveRepository>
        implements OpenOrderContract.Presenter {

    GoodsRepository goodsRepository;
    MemberRepository memberRepository;
    StockRepository stockRepository;

    @Override
    protected void initOtherRepository() {
        super.initOtherRepository();
        goodsRepository = new GoodsRepository();
        memberRepository = new MemberRepository();
        stockRepository = new StockRepository();
    }

    public void initEvent() {

        // 添加商品 Event
        Subscription addGoodsListener = RxBus.getDefault()
                .toObservable(AddGoodsEvent.class)
                .subscribe(new Action1<AddGoodsEvent>() {
                    @Override
                    public void call(AddGoodsEvent addGoodsEvent) {
                        mView.showGoodsAdded(addGoodsEvent.getGoodsEntityList());
                    }
                });
        addSubscrebe(addGoodsListener);

        // 添加服务 Event
        Subscription addServiceListener = RxBus.getDefault()
                .toObservable(AddServiceEvent.class)
                .subscribe(new Action1<AddServiceEvent>() {
                    @Override
                    public void call(AddServiceEvent addServiceEvent) {
                        mView.showServiceAdded(addServiceEvent.getServiceEntity());
                    }
                });
        addSubscrebe(addServiceListener);

        //结账
        Subscription settleListener = RxBus.getDefault()
                .toObservable(SettleSuccessEvent.class)
                .subscribe(new Action1<SettleSuccessEvent>() {
                    @Override
                    public void call(SettleSuccessEvent settleSuccessEvent) {
                        mView.showSettleSuccess();
                    }
                });
        addSubscrebe(settleListener);

        //修改预约时间
        Subscription updateReserveTimeListener = RxBus.getDefault()
                .toObservable(UpdateReserveTimeEvent.class)
                .subscribe(new Action1<UpdateReserveTimeEvent>() {
                    @Override
                    public void call(UpdateReserveTimeEvent updateReserveTimeEvent) {
                        mView.showReserveTimeChanged(updateReserveTimeEvent.getDate());
                    }
                });
        addSubscrebe(updateReserveTimeListener);

        //结账更新会员信息
        Subscription bindMemberListener = RxBus.getDefault()
                .toObservable(MemberBindEvent.class)
                .subscribe(new Action1<MemberBindEvent>() {
                    @Override
                    public void call(MemberBindEvent memberBindEvent) {
                        mView.showUpdateMemberSuccess(memberBindEvent.getMemberEntity());
                    }
                });
        addSubscrebe(bindMemberListener);

        Subscription remotePriceChangeListener = RxBus.getDefault()
                .toObservable(RemotePriceChangeEvent.class)
                .subscribe(new Action1<RemotePriceChangeEvent>() {
                    @Override
                    public void call(RemotePriceChangeEvent remotePriceChangeEvent) {
                        if (remotePriceChangeEvent.getType() == RemotePriceChangeEvent.TYPE_GOODS) {
                            mView.showGoodsPriceChanged();
                        } else {
                            mView.showServicePriceChanged();
                        }
                    }
                });
        addSubscrebe(remotePriceChangeListener);

    }

    @Override
    public void loadServerList(String updateType, String appointmentId, String appointmentTime, List<ServiceEntity> serviceList) {
        ApiCallBack<ServerResultEntity> callBack = new ApiCallBack<ServerResultEntity>() {
            @Override
            public void onSuccess(ServerResultEntity serverEntities) {
                mView.showServerList(serverEntities);
            }

            @Override
            public void onError(BaseResponse response) {
                mView.showError(response.getMsg());
            }
        };

        mRepo.getUsableTechnicianList(updateType, appointmentId, appointmentTime, serviceList, callBack);
        addSubscrebe(callBack);
    }


    @Override
    public void doAddReserve(String memberId, String username, String phone, List<ServiceEntity> serviceList) {
        if (ListUtil.isListEmpty(serviceList)) {
            mView.showError("请先添加服务");
            return;
        }
        ApiCallBack<ReserveOrderEntity> callBack = new ApiCallBack<ReserveOrderEntity>() {
            @Override
            public void onSuccess(ReserveOrderEntity reserveOrderEntity) {
                mView.showAddReserveSuccess(reserveOrderEntity);
            }

            @Override
            public void onError(BaseResponse response) {
                mView.showError(response.getMsg());
            }
        };

        mRepo.addReserve(AppUtil.hasServiceBusiness() ? ReserveOrderEntity.ORDER_TYPE_RESERVE
                        : ReserveOrderEntity.ORDER_TYPE_BABYSWIM, ReserveOrderEntity.ORDER_STATUS_ARRIVED,
                String.valueOf(System.currentTimeMillis()), memberId, username, phone, serviceList, callBack);
        addSubscrebe(callBack);
    }

    @Override
    public void doDeleteSubReserve(String subAppointOrderId) {
        ApiCallBack<String> callBack = new ApiCallBack<String>() {
            @Override
            public void onSuccess(String s) {
                mView.showDeleteSubReserveSuccess();
            }

            @Override
            public void onError(BaseResponse response) {
                mView.showError(response.getMsg());
            }
        };
        mRepo.deleteSubService(subAppointOrderId, callBack);
        addSubscrebe(callBack);
    }

    @Override
    public void doDeleteReserve(String appointmentId) {
        ApiCallBack<String> callBack = new ApiCallBack<String>() {
            @Override
            public void onSuccess(String s) {
                mView.showCloseReserveSuccess();
            }

            @Override
            public void onError(BaseResponse response) {
                mView.showError(response.getMsg());
            }
        };
        mRepo.deleteServe(appointmentId, callBack);
        addSubscrebe(callBack);
    }

    @Override
    public void doUpdateReserveServer(String subAppointOrderId, final String technicianId, final String technicianName) {
        ApiCallBack<String> callBack = new ApiCallBack<String>() {
            @Override
            public void onSuccess(String s) {
                mView.showUpdateServerSuccess(technicianId, technicianName);
            }

            @Override
            public void onError(BaseResponse response) {
                mView.showError(response.getMsg());
            }
        };
        mRepo.updateReserveService(subAppointOrderId, technicianId, technicianName, callBack);
        addSubscrebe(callBack);
    }

    @Override
    public void doQuicklyAddMember(String phone, String name, String gender, String level) {
        if (!isInputLegal(name, phone, level)) {
            return;
        }
        ApiCallBack<MemberEntity> callBack = new ApiCallBack<MemberEntity>() {
            @Override
            public void onSuccess(MemberEntity memberEntity) {
                mView.showAddMemberSuccess(memberEntity);
            }

            @Override
            public void onError(BaseResponse response) {
                mView.showError(response.getMsg());
            }
        };
        memberRepository.createNewMember(name, phone, gender, level, "",
                "", "", "", "", callBack);
    }

    @Override
    public void searchMember(String phone) {
        if (!PatternUtils.isMobileNO(phone)) {
            mView.showError("手机号格式不正确");
            return;
        }

        ApiCallBack<MemberEntity> callBack = new ApiCallBack<MemberEntity>() {
            @Override
            public void onSuccess(MemberEntity memberEntity) {
                mView.showSearchMemberSuccess(memberEntity);
            }

            @Override
            public void onError(BaseResponse response) {
                mView.showError(response.getMsg());
            }
        };
        memberRepository.getMemberInfoByPhone(phone, callBack);
        addSubscrebe(callBack);
    }

    @Override
    public void doConfirmArrived(String appointmentId) {
        ApiCallBack<String> callBack = new ApiCallBack<String>() {
            @Override
            public void onSuccess(String s) {
                mView.showConfirmArrivedSuccess();
            }

            @Override
            public void onError(BaseResponse response) {
                mView.showError(response.getMsg());
            }
        };
        mRepo.updateServeState(appointmentId, ReserveOrderEntity.ORDER_STATUS_ARRIVED, callBack);
        addSubscrebe(callBack);
    }

    @Override
    public void loadReserveDetail(String id) {
        ApiCallBack<ReserveOrderEntity> callBack = new ApiCallBack<ReserveOrderEntity>() {
            @Override
            public void onSuccess(ReserveOrderEntity reserveOrderEntity) {
                mView.showReserveDetail(reserveOrderEntity);
            }

            @Override
            public void onError(BaseResponse response) {
                mView.showError(response.getMsg());
            }
        };
        mRepo.selectOrderAppointmentDetail(id, AppUtil.hasServiceBusiness() ? "1" : "2", callBack);
        addSubscrebe(callBack);
    }

    @Override
    public void doUpdateReserveMember(String appointmentId, final MemberEntity memberEntity) {
        ApiCallBack<String> callBack = new ApiCallBack<String>() {
            @Override
            public void onSuccess(String s) {
                mView.showUpdateMemberSuccess(memberEntity);
            }

            @Override
            public void onError(BaseResponse response) {
                mView.showError(response.getMsg());
            }
        };
        mRepo.updateAppointmentInfo(appointmentId, memberEntity != null ? memberEntity.getMemberId() : "", callBack);
        addSubscrebe(callBack);
    }

    @Override
    public void checkGoodInInventory(List<GoodsEntity> goodsEntities) {
        ApiCallBack<List<GoodsEntity>> callBack = new ApiCallBack<List<GoodsEntity>>() {
            @Override
            public void onSuccess(List<GoodsEntity> goodsEntities) {
                mView.showCheckResult(goodsEntities);
            }

            @Override
            public void onError(BaseResponse response) {
                mView.showError(response.getMsg());
            }
        };

        List<String> goodsIds = new ArrayList<>();
        for (GoodsEntity entity : goodsEntities) {
            goodsIds.add(entity.getGoodsSkuId());
        }
        stockRepository.checkInTheInventory(goodsIds, callBack);
        addSubscrebe(callBack);
    }

    @Override
    public void loadRemoteGoodsPrice(List<GoodsEntity> goodsList, MemberEntity memberEntity) {
        if (ListUtil.isListEmpty(goodsList)) {
            return;
        }
        ApiCallBack<PageListResponse<GoodsEntity>> callBack = new ApiCallBack<PageListResponse<GoodsEntity>>() {
            @Override
            public void onSuccess(PageListResponse<GoodsEntity> response) {
                mView.showSyncRemoteGoodsPrice(response.getList());
            }

            @Override
            public void onError(BaseResponse response) {
            }
        };
        List<String> goodsIds = new ArrayList<>();
        for (GoodsEntity goodsEntity : goodsList) {
            goodsIds.add(goodsEntity.getGoodsSkuId());
        }
        goodsRepository.selectGoodsPrice(JSON.toJSONString(goodsIds), memberEntity, callBack);
        addSubscrebe(callBack);
    }

    private void clearCart() {
        ApiCallBack<String> callBack = new ApiCallBack<String>() {
            @Override
            public void onSuccess(String s) {
                mView.dismissLoadingDialog();
//                mView.showClearCart();
            }

            @Override
            public void onError(BaseResponse response) {
                mView.dismissLoadingDialog();
                mView.showError(response.getMsg());

            }
        };
        goodsRepository.clearCartGoods(callBack);
        addSubscrebe(callBack);
    }

    public void addGoodsToCart(final boolean isModify, Object cartList) {

        // 实时同步购物车数据
        clearCart();

        ApiCallBack<String> callBack = new ApiCallBack<String>() {
            @Override
            public void onSuccess(String s) {
                mView.dismissLoadingDialog();
                mView.showAddGoodsSuccess(isModify);
            }

            @Override
            public void onError(BaseResponse response) {
                mView.dismissLoadingDialog();
                mView.showError(response.getMsg());

            }
        };
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", JSON.toJSON(cartList));
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
        goodsRepository.addGoodsToCartBatch(body, callBack);
        addSubscrebe(callBack);
    }

    private boolean isInputLegal(String name, String phone, String level) {

        if (TextUtils.isEmpty(name)) {
            mView.showError("请输入会员姓名");
            return false;
        }

        if (!PatternUtils.checkName(name)) {
            mView.showError("会员姓名不能输入特殊字符");
            return false;
        }

        if (!PatternUtils.isMobileNO(phone)) {
            mView.showError("手机号格式不正确");
            return false;
        }

        if (TextUtils.isEmpty(level)) {
            mView.showError("请选择会员等级");
            return false;
        }

        return true;
    }
}
